package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private DatagramSocket socket;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    //启动客户端
    public void start() throws IOException {
        Scanner scan = new Scanner(System.in);
        while(true) {
            //从控制台读取用户的数据
            System.out.println("请输入要发送的内容：");
            if(!scan.hasNext()) {
                break;
            }
            String request = scan.nextLine();
            //将请求发送给服务器，构造DatagramPacket 对象
            //构造过程中同时将服务器的IP 和 端口号传入
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);

            //3.发送数据报
            socket.send(requestPacket);

            //4.接收响应的数据报
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            //5.从服务器获取的数据报中进行数据的解析工作并打印出来。
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9091);
        client.start();
    }
}
